#!/bin/bash

cpu=4 # the num of cpu used to make

[ -z $PYTHON3_HOME ] && PYTHON3_HOME="$HOME/dev/Python3.4"
pipconf="$HOME/.pip/pip.conf"

tmpdir=$(mktemp -d /tmp/python.XXXX);
trap 'rm -rf "$tmpdir"' EXIT
set -e

cat <<EOF >$tmpdir/greplist
pip
tensorflow
EOF

cat <<EOF > $tmpdir/pip.conf
[global]
trusted-host=mirrors.aliyun.com
index-url=http://mirrors.aliyun.com/pypi/simple/
[list]
format=legacy 
EOF

# for test
# cat $tmpdir/greplist
# cat $tmpdir/pip.conf

function check_pipconf {

  if [ -f $pipconf ] ;then
    if ! cmp -s $pipconf $tmpdir/pip.conf; then
      mv $pipconf $pipconf.bak
      cp $tmpdir/pip.conf $pipconf
    fi
  else
    cp $tmpdir/pip.conf $pipconf
  fi

}

function check_source {

  if [ ! -s Python-3.4.5.tgz ]; then
    echo "download the Python package"
    wget https://www.python.org/ftp/python/3.4.5/Python-3.4.5.tgz || exit 1
  fi
  tar -zxvf Python-3.4.5.tgz || exit 1
}

function gen_package_list {
  echo "generate pip list"
  pip3 list | cut -f1 -d' '  > list
}


function python_install {
  check_source
  [ -d $PYTHON3_HOME ] && mv $PYTHON3_HOME $PYTHON3_HOME.bak
  cd Python-3.4.5
  ./configure --prefix=$PYTHON3_HOME --enable-shared --enable-loadable-sqlite-extensions CFLAGS=-fPIC || exit 1
  make -j $cpu || exit 1
  make install
}

function package_install {
  export PYTHON3_HOME=$PYTHON3_HOME
  export PATH=$PYTHON3_HOME/bin:$PATH
  export LD_LIBRARY_PATH=$PYTHON3_HOME/lib:$LD_LIBRARY_PATH
  pip3 install --upgrade pip
  [ -f list ] && cat list | grep -v -f $tmpdir/greplist | xargs -I {} pip3 install {}
  
}

# gen_package_list
# python_install
package_install



